<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Event</title>
</head>
<body>
<script type="text/javascript">
class EventEmitter {
	constructor() {
		this._events = [];
	}
	on(event, cb) {
		const queue = this._events[event] || [];
		queue.push(cb);
		this._events[event] = queue;
		return this;
	}
	off(event, cb) {
		if(event) {
			const queue = this._events[event] || [];
			if(cb) {
				this._events[event] = queue.filter((fn) => {
					return cb !== fn;
				});
			}else {
				delete this._events[event]
			}
			
			return this;
		}else {
			this._events = [];
		}
	}
	emit(event, ...args) {
		if(event) {
			const queue = this._events[event] || [];
			queue.forEach((cb) => {
				cb(...args);
			});
		}else {
			for(let key in this._events) {
				const queue = this._events[key] || [];
				queue.forEach((cb) => {
					cb(...args);
				});
			};
		}
		return this;
	}
}
</script>
<script type="text/javascript">
const event1 = new EventEmitter();
const event2 = new EventEmitter();
event1.on('aa', (x, y) => {
	console.log('aa', x, y);
}).on('aa', (x, y) => {
	console.log('aa', x, y);
}).on('bb', (x, y) => {
	console.log('bb', x, y);
});

event1.emit('bb', 33, 44);
event1.off('aa');
console.log(event1);
console.log(event2);
</script>
</body>
</html>